package com.chatcompetition.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chatcompetition.common.utils.JwtTokenUtil;
import com.chatcompetition.domain.dto.AdminUserDetails;
import com.chatcompetition.domain.entity.Employee;
import com.chatcompetition.domain.model.UmsResource;
import com.chatcompetition.domain.vo.EmployeeLoginVO;
import com.chatcompetition.mapper.EmployeeMapper;
import com.chatcompetition.mapper.UmsResourceMapper;
import com.chatcompetition.service.EmployeeService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    private static final Logger LOGGER = LoggerFactory.getLogger(EmployeeServiceImpl.class);
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private UmsResourceMapper umsResourceMapper;


    @Override
    public EmployeeLoginVO login(String employeeNumber, String employeePassword, String employeeDepartment) {
        String token = null;
        //密码需要客户端加密后传递
        try {
            UserDetails userDetails = getAdminUserDetailsByEmployeeNumber1(employeeNumber);
//            if(!passwordEncoder.matches(employeePassword,userDetails.getPassword())){
//                throw new AuthenticationException("用户名或密码错误");
//            }
//            if(!userDetails.isEnabled()){
//                throw new AuthenticationException("账号已被禁用");
//            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);

//            updateLoginTimeByUsername(username);
        } catch (AuthenticationException e) {
            LOGGER.warn("登录异常:{}", e.getMessage());
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        EmployeeLoginVO employeeLoginVO = new EmployeeLoginVO();
        Employee employee = employeeMapper.findByEmployeeNumberAndEmployeePasswordAndDepartment(employeeNumber, employeePassword, employeeDepartment);
        employeeLoginVO.setEmployeeNumber(employee.getEmployeeNumber());
        employeeLoginVO.setName(employee.getName());
        employeeLoginVO.setEmployeeDepartment(employee.getEmployeeDepartment());
        employeeLoginVO.setTokenMap(tokenMap);

        return employeeLoginVO;
    }


    @Override
    public List<Employee> getAllEmployees() {
        return employeeMapper.selectList(null);
    }

    @Override
    public void deleteEmployee(Integer id) {
        employeeMapper.deleteById(id);
    }

    @Override
    public Employee addEmployee(Employee employee) {
        employeeMapper.insert(employee);
        return employee;
    }

    @Override
    public boolean updateEmployeeByEmployeeNumber(Employee employee) {
        // 使用 UpdateWrapper 构建更新条件
        UpdateWrapper<Employee> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("employee_number", employee.getEmployeeNumber());

        // 更新员工信息
        return employeeMapper.update(employee, updateWrapper) > 0;
    }
    @Override
    public boolean deleteByEmployeeNumber(String employeeNumber) {
        // 使用 QueryWrapper 构建查询条件
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("employee_number", employeeNumber);

        // 根据工号删除员工
        return employeeMapper.delete(queryWrapper) > 0;
    }

    @Override
    public boolean updateEmployeeStatusByEmployeeNumber(String employeeNumber, int employeeStatus) {
        // 使用 UpdateWrapper 构建更新条件
        UpdateWrapper<Employee> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("employee_number", employeeNumber);

        // 创建一个 Employee 对象，只更新 employeeStatus 字段
        Employee employee = new Employee();
        employee.setEmployeeStatus(employeeStatus);

        // 更新员工状态
        return employeeMapper.update(employee, updateWrapper) > 0;
    }

    @Override
    public Employee getEmployeeByEmployeeNumber(String employeeNumber) {
        return baseMapper.selectOne(new QueryWrapper<Employee>().eq("name", employeeNumber));
    }

    public Employee getEmployeeByEmployeeNumber1(String employeeNumber) {
        return baseMapper.selectOne(new QueryWrapper<Employee>().eq("employee_number", employeeNumber));
    }
    @Override
    public AdminUserDetails getAdminUserDetailsByEmployeeNumber(String employeeNumber) {
        Employee employee = getEmployeeByEmployeeNumber(employeeNumber);
        if (employee != null) {
            List<UmsResource> resourceList = getResourceList(employee.getId());
            return new AdminUserDetails(employee,resourceList);
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }



    @Override
    public void addRoleRelation(Long id, String employeeDepartment) {

        Integer employeeRoleIdByEmployeeDepartment = employeeMapper.findRoleIdByEmployeeDepartment(employeeDepartment);
        employeeMapper.insertRoleRelation(id, Long.valueOf(employeeRoleIdByEmployeeDepartment));
    }

    @Override
    public void updateRoleRelation(Long id, String employeeDepartment) {
        Integer employeeRoleIdByEmployeeDepartment = employeeMapper.findRoleIdByEmployeeDepartment(employeeDepartment);
        employeeMapper.updateRoleRelation(id, Long.valueOf(employeeRoleIdByEmployeeDepartment));
    }

    public AdminUserDetails getAdminUserDetailsByEmployeeNumber1(String employeeNumber) {
        Employee employee = getEmployeeByEmployeeNumber1(employeeNumber);
        if (employee != null) {
            List<UmsResource> resourceList = getResourceList(employee.getId());
            return new AdminUserDetails(employee,resourceList);
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }
    private List<UmsResource> getResourceList(Long id) {
        return umsResourceMapper.selectResourceListByAdminId(id);
    }

    @Override
    public Integer getEmployeeStatusByEmployeeNumber(String employeeNumber) {
        // 调用 Mapper 层方法，查询员工的 employee_status
        return employeeMapper.findEmployeeStatusByEmployeeNumber(employeeNumber);
    }


}